package com.ocom.emqx.timer;

import com.ocom.common.utils.ThreadTaskUtils;
import com.ocom.emqx.client.PayoperFeignService;
import com.ocom.emqx.handle.MqttSendClient;
import com.ocom.emqx.vo.QrCodePayingVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;


@Component
public class ScheduledService {

    @Autowired
    private PayoperFeignService payoperFeignService;

    @Autowired
    MqttSendClient mqttSendClient;

    @Resource
    private RedisUtil redisUtil;

    public Logger log = LoggerFactory.getLogger(ScheduledService.class);

//    @Scheduled(cron = "0/5 * * * * *")
//    public void scheduled(){
//        log.info("=====>>>>>使用cron  {}",System.currentTimeMillis());
//    }


    //发起定时查询
    @Scheduled(fixedRate = 4000)
    public void scheduled1() {
//        log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
        Set<Object> rangeByScore = redisUtil.rangeByScore("mqtt:orderPaying", System.currentTimeMillis() - 1000l * 60l, System.currentTimeMillis());
        if (rangeByScore == null || rangeByScore.size() == 0) {
            return;
        }
        log.info("定时任务查询 【{}】",rangeByScore);
        for (Object obj : rangeByScore) {
            QrCodePayingVo qrCodePayingVo = (QrCodePayingVo) obj;
            String canKey = "mqtt:orderSearch:" + qrCodePayingVo.getTradeNo();
            Object search = redisUtil.get(canKey);
            if (search != null && ((Integer) search) == 1) {
                continue;
            }
            //开始查询
            redisUtil.set("mqtt:orderSearch:" + qrCodePayingVo.getTradeNo(), 1, 70l);
            ThreadTaskUtils.run(new UserRunnableTask(qrCodePayingVo, redisUtil, mqttSendClient, payoperFeignService,log));
        }
    }

    //移除过期key
    @Scheduled(fixedDelay = 20000)
    public void scheduled2() {
//        log.info("=====>>>>>fixedDelay{}","定时任务移除过期value");
        redisUtil.zDel("mqtt:orderPaying", 0l, System.currentTimeMillis() - 1000l * 60l);
    }
}
